<template>
    <el-container class="container">
      <el-header height="50px" class="header">
        <span>电源机组类型</span>
        <el-select v-model="SelectedPowerTypeCode" placeholder="请选择">
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="item in powerTypeList"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
        <span>开始日期</span>
        <el-date-picker class="year" v-model="startYear" type="year"></el-date-picker>
        <span>结束日期</span>
        <el-date-picker class="year" v-model="endYear" type="year"></el-date-picker>
        <el-button type="primary" class="dateBtn" @click="queryData">查询</el-button>
      </el-header>
      <el-main class="main">
        <div id="map" ref="map"></div>
      </el-main>
    </el-container>
</template>

<script>
import * as echarts from "echarts";
import zhongguo from "@/utils/china.json";
import { queryPowerTypeList,queryEchartsData } from "@/services/powerEvolution"
export default {
  data() {
    return {
      startYear: new Date(),
      endYear:new Date(),
      powerTypeList:[],//电源机组类型
      SelectedPowerTypeCode:'',//选中的电源机组类型code
      echartsData:{
        data:[],
        timeLine:[],
        nameList:[],
        valueList:[],
        max:[],
        min:[],
      }, 
    };
  },
  computed: {},
  methods: {
    //查询电源机组列表
    async queryPowerTypeList () {
      try{
        const res = await queryPowerTypeList({});
        this.powerTypeList = res.respData;
      } catch (e) {
        this.$message.error(e.respMessage);
      }
    },
    async queryEchartsData () {
        const start = +new Date(this.startYear).getFullYear();
        const end = +new Date(this.endYear).getFullYear();
        const res = await queryEchartsData({'code':this.SelectedPowerTypeCode,'startDate':start,'endDate':end})
        if(res.respCode===500){
          this.$message.error(res.respMessage)
          return 
        }
        const temp = res.respData.data
        // 替换数据中的省
        temp.forEach(father => {
          father.forEach(child => {
            child.name = child.name.replace(/省/,'')
          })
        });
        this.echartsData.data = temp
        this.echartsData.nameList = res.respData.nameList
        this.echartsData.valueList = res.respData.valueList
        this.echartsData.max = res.respData.maxList
        this.echartsData.min = res.respData.minList
        this.echartsData.timeLine = res.respData.timeLine
        // 初始化Echarts图
        this.initEcharts();

    },
    //地图和柱状图
    initEcharts () {
      var myChart = echarts.init(this.$refs.map);
      const dataList = this.echartsData
      const len = dataList.data.length
      const option = {
        //时间轴
				timeline: {
					// `timeline.data` 中的每一项，对应于 `options`
					// 数组中的每个 `option`
					data: dataList.timeLine,
          silent: true,
          axisType: "value",
          tooltip:{
            show:false
          },
          checkpointStyle:{
            color:'rgb(50,205,50)'
          },
          progress:{
            lineStyle:{
              color:'rgb(50,205,50)'
            },
            itemStyle:{
              color:'rgb(50,205,50)'
            }
          }
				},
        // 背景颜色
        backgroundColor: "#FFF",
        tooltip: {
          trigger: 'item',
          showDelay: 0,
          transitionDuration: 0.2,
          formatter(params) {
            return `装机容量</br>${params.name} : ${params.value||params.value===0?params.value:"-"}kW`;
          },
        },
        visualMap: {
          left: 'right',
          min: dataList.min[0]?dataList.min[0]:0,
          max: dataList.max[0]?dataList.max[0]:500,
          seriesIndex:0,
          inRange: {
            color: [
              '#8ED885',
              '#6BCA5F',
              '#4CB83E',
              '#3D9132',
              '#2E6B26',
            ]
          },
          calculable: true
        },
        grid: {
          right: "10%",
          top: "8%",
          bottom: "20%",
          width: '30%'
        },
        xAxis: {
          type: 'value',
          position: 'top',
          name: '机组容量 kW',
          axisLine:{
            show:true,
          }
        },
				options:[
					{
            yAxis: {
              type: 'category',
              name: '地区',
              nameLocation:'start',
              data: [],
              axisTick:{
                inside: true,
                length: 3 
              },
            },
						series: [
              {
                type:'map',
                map:'china',
                left: '10%',   // 控制地图左边距
                top: '0%',    // 控制地图上边距
                label: {
                  // 通常状态下的样式
                  normal: {
                    show: true,
                    fontStyle:'italic',
                    fontWeight:'bold',
                    fontSize:'10', 
                    textStyle: {
                      color: "#000",
                    },
                  },
                  // 鼠标放上去的样式
                  emphasis: {
                    textStyle: {
                      color: "#000",
                    },
                  },
                },
                // 地图区域的样式设置
                itemStyle: {
                  normal: {
                    borderColor: "#000",
                    borderWidth: 1,
                    areaColor: {
                      type: "radial",
                      x: 0.5,
                      y: 0.5,
                      r: 0.8,
                      colorStops: [
                        {
                          offset: 0,
                          color: "rgba(0, 0, 0, 0)", // 0% 处的颜色
                        },
                        {
                          offset: 1,
                          color: "rgba(255, 255, 255, 0)", // 100% 处的颜色
                        },
                      ],
                      globalCoord: false, // 缺省为 false
                    },
                  },
                  // 鼠标放上去高亮的样式
                  emphasis: {
                    areaColor: "#4FC4BF",
                    borderWidth: 0.1,
                    borderColor:'#FFF'
                  },
                },
                // 数据格式，其中name,value是必要的，value的前两个值是数据点的经纬度，其他的数据格式可以自定义
                data: [],
                showEffectOn: "render",
                rippleEffect: {
                    brushType: "stroke",
                },
                hoverAnimation: true,
                zlevel: 1,
              },
              {
                type: "bar",
                itemStyle: {
                  color: 'rgb(50,205,50)', // 设置柱状图的颜色
                },
                data: [],
              }
						],
					},
          
				],
      };
      
      for(let i = 0;i < len;i++){
        const obj = JSON.parse(JSON.stringify(option.options[0]))
        obj.series[0].data = dataList.data[i]
        obj.series[1].data = dataList.valueList[i].reverse()
        obj.yAxis.data = dataList.nameList[i].reverse()
        option.options.push(obj)
      }
      if(option.options.length!==1) option.options.shift()
      echarts.registerMap("china", zhongguo);
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);

      //时间轴与Echarts图解绑事件
      myChart.off('timelinechanged')
      //时间轴年份改变事件
      myChart.on("timelinechanged", function (params) {
        let index = params.currentIndex;
        option.visualMap.max = dataList.max[index];
        option.visualMap.min = dataList.min[index];
        myChart.setOption(option);
      });
    },
    //查询数据
    async queryData () {
      const start = +new Date(this.startYear).getFullYear();
      const end = +new Date(this.endYear).getFullYear();
      if(start > end){
        this.$message.error('开始年份不能大于结束年份');
        return 
      }
      this.queryEchartsData();
    },
  },
  created() {
    this.queryPowerTypeList();
    this.queryEchartsData();
  },
  mounted() {

  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: calc(100% - 40px);
  .header {
    width: 660px;
    display: flex;
    justify-content:space-between;
    align-items: center;
    ::v-deep .el-input {
      width: 100px;
    }
    .dateBtn {
      width: 50px;
    }
  }
  .main {
    width: 100%;
    height: 100%;
    #map {
      width: 100%;
      height: 100%;
    }
  }
}


</style>